package com.jinxiangyang.utils.oos;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


/**
 * TODO
 *
 * @Author Xenon
 * @Date 2023/8/15 17:08
 */
public class OOSUtils{


    public static  String endpoint;
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    public static String accessKeyId;
    public static String accessKeySecret;

    public static String bucketName;
    static {
          endpoint = "oss-rg-china-mainland.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
          accessKeyId = "LTAI5tGjsXBrJsCFm27Hm9mE";
          accessKeySecret = "FZmLC47hk0AWpSBho9TYVwQ0vp8Kn5";

          bucketName = "xenon-test01";
    }

    public static OSS getOss(){
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.createBucket(bucketName);
        return oss;
    }

    public static String getBucketName(){
        return bucketName;
    }

    public static String getEndpoint(){
        return endpoint;
    }

    public static String avatarUpload(MultipartFile file) {

        OSS ossClient = OOSUtils.getOss();
        String bucketName = OOSUtils.getBucketName();
        String filename = file.getOriginalFilename();
        String url = "";
        try {
            ossClient.putObject(bucketName,filename,file.getInputStream());

            //http://xenon-test01.oss-rg-china-mainland.aliyuncs.com/IMG_20230303_112502.jpg
            url = "http://"+bucketName+"."+OOSUtils.getEndpoint()+"/"+filename;

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
